<?php

namespace humhub\modules\api\controllers;

use Yii;
use yii\helpers\Url;
use humhub\modules\directory\widgets\Sidebar;
use humhub\modules\user\models\User;
use humhub\modules\space\models\Space;
use humhub\modules\content\models\Content;
use humhub\modules\post\models\Post;
use humhub\modules\api\models\TopList;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 获取目录菜单下的:内容流、成员列表 和 板块列表, 板块列表可以筛选:(发现) 任务, 课程, 院校. 新增：导师(U师)列表
 */
class DirectoryController extends Base4GuestController
{

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
            'guestAllowedActions' => ['groups', 'index', 'members', 'spaces', 'user-posts', 'stream']
        ];

        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        $actions = parent::actions();
        unset($actions['update'], $actions['create'], $actions['index'], $actions['delete']);
        return $actions;

        return [
            'stream' => [
                'class' => \humhub\modules\api\cccstream\UserPostsStreamAction::className(),
                'mode' => \humhub\modules\api\cccstream\UserPostsStreamAction::MODE_NORMAL,
            ],
        ];
    }

    /**
     * 获取目录菜单下的内容流
     *
     * GET api/directory/stream?limit=[4]&filters=&sort=c&from=[66]&mode=normal
     *
     * get.limit : 单次获取总量
     *
     * get.from : 起始wallEntryID，默认为空''=第一页
     *
     * get.p_type : 类型筛选: 空=全部, 0=图文, 1=任务, 2=课程, 3=视频 (可用于发现:任务／课程) ,4=八卦
     *
     * get.p1type : 筛选任务: 空=全部, 1=报名中， 2=进行中，3=已完成
     *
     * 列表中任务状态显示规则(times是当前时间戳，在output中有返回)： if(s_t1>times)=报名中;  if(s_t1<times AND s_t2>times)=进行中; if(s_t2<times)=已完成;
     *
     * @return array  output:返回的内容, counter:表示获取几个wallEntry,  entryIds:表示所有返回的wallEntryID, lastEntryId:列表中最后一个EntryId
     */
    public function actionStream(){

        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\UserPostsStreamAction::className(),
            'mode' => \humhub\modules\api\cccstream\UserPostsStreamAction::MODE_NORMAL,
        ], ['stream', $this]);
        return $stream->run();
    }

    /**
     * 获取发现-推荐位列表
     *
     * GET api/directory/toplist
     *
     * @return ad广告位, list推荐列表
     */
    public function actionToplist(){
        return TopList::getList(5);
    }

    /**
     * 获取发现-推荐位列表内的内容
     *
     * GET api/directory/tops?limit=[4]&filters=&sort=c&from=[66]&mode=normal
     *
     * get.top_id 推荐列表中的top.id( [change]->topid )
     */
    public function actionTops(){
        $_GET['top_id'] = (int)$_GET['top_id'];
        $top = (new \yii\db\Query())
            ->select("title, imgguid, postcount")
            ->from('post_top')->where('topid='.$_GET['top_id'].' AND status=1')->count();
        if( ! $top ){
            Yii::$app->params['res-success'] = false;
            return false;
        }

        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\UserPostsStreamAction2::className(),
            'mode' => \humhub\modules\api\cccstream\UserPostsStreamAction2::MODE_NORMAL,
        ], ['stream', $this]);
        return $stream->run();
    }

    /**
     * 获取*成员*列表
     *
     * GET /api/directory/members
     *
     * get.keyword 支持搜索, 默认返回所有成员
     *
     * @return array keyword:关键字, count:总用户(!不是列表总数!), users:成员列表(部分字段说明: follow:当前可以关注的操作,值=follow表示可以关注,=unfollow表示可以取消关注,=''无操作), tags:每个用户最多返回5个tag.
     */
    public function actionMembers(){
        $keyword = Yii::$app->request->get('keyword', "");
        $page = (int) Yii::$app->request->get('page', 1);
        $groupId = (int) Yii::$app->request->get('groupId', "");

        $group = null;
        if ($groupId) {
            $group = \humhub\modules\user\models\Group::findOne(['id' => $groupId, 'show_at_directory' => 1]);
        }

        $searchOptions = [
            'model' => \humhub\modules\user\models\User::className(),
            'page' => $page,
            //'pageSize' => $this->module->pageSize,
            'pageSize' => 20,
        ];

        //if ($this->module->memberListSortField != "") {
        //    $searchOptions['sortField'] = $this->module->memberListSortField;
        //}

        if ($group !== null) {
            $searchOptions['filters'] = ['groups' => $group->id];
        }

        $searchResultSet = Yii::$app->search->find($keyword, $searchOptions);

        //$pagination = new \yii\data\Pagination(['totalCount' => $searchResultSet->total, 'pageSize' => $searchResultSet->pageSize]);
        //$userCount = User::find()->active()->count();
        $userCount = $searchResultSet->total;
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        \yii\base\Event::on(Sidebar::className(), Sidebar::EVENT_INIT, function($event) {
            $event->sender->addWidget(\humhub\modules\directory\widgets\NewMembers::className(), [], ['sortOrder' => 10]);
            $event->sender->addWidget(\humhub\modules\directory\widgets\MemberStatistics::className(), [], ['sortOrder' => 20]);
        });

        $u = [];
        $users = $searchResultSet->getResultInstances();
        foreach ($users as $user){
            $d['follow'] = \humhub\modules\api\models\Follow::getFollow($user);
            $d['guid'] = $user->guid;
            $d['img'] = $user->getProfileImage()->getUrl();
            $d['displayname'] =  $user->displayName;
            if ($user->hasGroup()){
                //implode(', ', array_map(function($g) {
                //    return Html::encode($g->name);
                //}, $user->groups));
            }
            $d['title'] = $user->profile->title;
            $d['tags'] = [];
            if( $user->hasTags() ){
                $tag = array_chunk($user->getTags(), 5);
                $d['tags'] = $tag[0];
            }

            $u[] = $d;
        }

        return array(
            'keyword' => $keyword,
            //'group' => $group,
            'count' => $userCount,
            'users' => $u,
            //'pagination' => $pagination
        );
    }

    /**
     * 获取*板块*列表
     *
     * GET /api/directory/spaces
     *
     * get.keyword 支持搜索, 默认返回所有可见板块
     *
     * get.s_type : 新增筛选条件-类型筛选: 空=全部, 1=任务, 2=课程, 5=院校
     *
     * @return array keyword:关键字, count:总板块(!不是列表总数!), chidden:隐藏板块, smore:大多数成员的板块, spaces:板块列表(部分字段说明:ismember:是否属于成员=1是,=0否, tags:每个用户最多返回5个tag, postcount:Post总数)
     */
    public function actionSpaces(){
        $keyword = Yii::$app->request->get('keyword', "");
        $page    = (int) Yii::$app->request->get('page', 1);
        $s_type  = (int) Yii::$app->request->get('s_type', 0);

        $searchOptions = [
            'model' => \humhub\modules\space\models\Space::className(),
            'page' => $page,
            'sortField' => ($keyword == '') ? 'title' : null,
            //'pageSize' => $this->module->pageSize,
            'pageSize' => 20,
        ];
        if( $s_type==1 || $s_type==2 || $s_type==5 ){
            $searchOptions['filters'] = ['s_type' => $s_type];
        }
        $searchResultSet = Yii::$app->search->find($keyword, $searchOptions);

        $statsCountSpaces = Space::find()->count();
        $statsCountSpacesHidden = Space::find()->where(['visibility' => Space::VISIBILITY_NONE])->count();
        $statsSpaceMostMembers = Space::find()->where('id = (SELECT space_id  FROM space_membership GROUP BY space_id ORDER BY count(*) DESC LIMIT 1)')->one();
        //$pagination = new \yii\data\Pagination(['totalCount' => $searchResultSet->total, 'pageSize' => $searchResultSet->pageSize]);
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        \yii\base\Event::on(Sidebar::className(), Sidebar::EVENT_INIT, function($event) {
            $event->sender->addWidget(\humhub\modules\directory\widgets\NewSpaces::className(), [], ['sortOrder' => 10]);
            $event->sender->addWidget(\humhub\modules\directory\widgets\SpaceStatistics::className(), [], ['sortOrder' => 20]);
        });

        $spaces = $searchResultSet->getResultInstances();
        $s = [];
        foreach($spaces as $space){
            //$d['follow'] = $this->getSpaceFollw($space);
            $d['ismember'] = 0;
            if ($space->isMember()) {
                $d['ismember'] = 1;
            }

            $d['img'] = $space->getProfileImage()->getUrl();

            $d['guid'] = $space->guid;

            $d['name'] = $space->name;
            $d['description'] = $space->description;

            $d['tags'] = [];
            if( $space->hasTags() ){
                $tag = array_chunk($space->getTags(), 5);
                $d['tags'] = $tag[0];
            }

            $d['s_type'] = $space->s_type;
            $d['s_v'] = $space->s_v; //+V
            //$d['s_img'] = $space->s_img;
            $d['s_img'] = '';
            $_file = \humhub\modules\file\models\File::findOne(['guid' => $space->s_img]);
            if( $_file ){
                if ($_file->getMimeBaseType() == "image"){
                    $d['s_img']  = $_file->getPreviewImageUrl(200, 200);
                }
            }

            if( ! is_object($space->contentContainerRecord) ){
                continue;
            }
            if ($s_type==5){
                $d['postcount'] = Content::find()->where([
                    'object_model' => Post::className(),
                    'created_by' => $space->created_by,
                    //'contentcontainer_id' => $space->id,
                ])->count();
            }else{
                $d['postcount'] = Content::find()->where([
                    'object_model' => Post::className(),
                    'contentcontainer_id' => $space->contentContainerRecord->id,
                    //'contentcontainer_id' => $space->id,
                ])->count();
            }


            $s[] = $d;
        }

        return array(
            'keyword' => $keyword,
            //'spaces' => $searchResultSet->getResultInstances(),
            //'count' => $statsCountSpaces,
            //'chidden' => $statsCountSpacesHidden,
            //'smore' => isset($statsSpaceMostMembers['name'])?$statsSpaceMostMembers['name']:'',
            'spaces' => $s,
            //'pagination' => $pagination,
        );
    }

    /**
     * 获取导师列表
     *
     * GET /api/directory/ushilist
     *
     * @return array 结构同粉丝列表
     */
    public function actionUshilist(){
        $query = User::find();
        $query->where('u_v=1');
        $query->active();

        //$query->count()
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => 20,
            'validatePage' => false,
        ]);

        $users = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        $u = [];
        foreach($users AS $user){
            $uone['guid']         = $user->guid;
            $uone['profileimage'] = $user->getProfileImage()->getUrl();
            $uone['displayname']  = $user->displayName;
            $uone['title']        = $user->profile->title;
            $uone['follow']       = \humhub\modules\api\models\Follow::getFollow($user, Yii::$app->user->id);
            $uone['countFollowers'] = $user->getFollowerCount(); //被关注
            $uone['u_v']          = $user->u_v;
            $u[] = $uone;
        }
        return $u;
    }

    /**
     * @inheritdoc
     */
    private function getSpaceFollw($space){
        if (Yii::$app->user->isGuest || $space->isMember()) {
            return '';
        }
        if ($space->isFollowedByUser()) {
            return 'unfollow';
        } else {
            return 'follow';
        }
    }
}
